package handler

import (
	"time"

	"gorm.io/gorm"

	"ssforward/common/constant"
	"ssforward/common/dto"
	"ssforward/common/enums"
	"ssforward/internal/forward/models"
)

type HandleCtrl int

const (
	HttpForward HandleCtrl = iota + 1
	MqttForward
	DbForward
)

// 自定义返回枚举类型
type handleCtrlType struct {
	TypeName    string
	ForwardFunc func(db *gorm.DB, ruleConfig map[string]interface{}, jsonData map[string]interface{})
}

func (it HandleCtrl) Get() handleCtrlType {
	switch it {
	case HttpForward:
		return handleCtrlType{TypeName: enums.Http.Get().Value, ForwardFunc: func(db *gorm.DB, ruleConfig map[string]interface{}, jsonData map[string]interface{}) {
			handler := &HttpForwardHandler{}
			handler.Orm = db
			handler.ForwardData(ruleConfig, jsonData)
		}}
	case MqttForward:
		return handleCtrlType{TypeName: enums.Mqtt.Get().Value, ForwardFunc: func(db *gorm.DB, ruleConfig map[string]interface{}, jsonData map[string]interface{}) {
			handler := &MqttForwardHandler{}
			handler.Orm = db
			handler.ForwardData(ruleConfig, jsonData)
		}}
	case DbForward:
		return handleCtrlType{TypeName: enums.Database.Get().Value, ForwardFunc: func(db *gorm.DB, ruleConfig map[string]interface{}, jsonData map[string]interface{}) {
			handler := &DbForwardHandler{}
			handler.Orm = db
			handler.ForwardData(ruleConfig, jsonData)
		}}
	default:
		return handleCtrlType{ForwardFunc: func(db *gorm.DB, ruleConfig map[string]interface{}, jsonData map[string]interface{}) {}}
	}
}

func GetHandlerCtrl(typeName string) handleCtrlType {
	switch typeName {
	case HttpForward.Get().TypeName:
		return HttpForward.Get()
	case MqttForward.Get().TypeName:
		return MqttForward.Get()
	case DbForward.Get().TypeName:
		return DbForward.Get()
	default:
		return handleCtrlType{ForwardFunc: func(db *gorm.DB, ruleConfig map[string]interface{}, jsonData map[string]interface{}) {}}
	}
}

func addToDetail(serverId string) {
	constant.DataDetailQueue.Enqueue(models.SysDataDetail{
		Type:       "DATA_FORWARD_NUM",
		Key:        serverId,
		Value:      1,
		CreateTime: dto.LocalTime(time.Now()),
	})
}
